var lhsList = new Array();
var rhsList = new Array();
Array.prototype.contains = function(element) {
	for ( var i = 0; i < this.length; i++) {
		try {
			if (this[i] == element || this[i].id == element.id) {
				return true;
			}
		} catch (ex) {
		}
	}
	return false;
}

var paymentTerms = [ {
	id : "US00",
	desc : "US00-Net 1 Day"
}, {
	id : "US01",
	desc : "US01-Net 2 Days"
}, {
	id : "US02",
	desc : "US02-1% discount if paid within 10 days, Net 30 days"
}, {
	id : "US03",
	desc : "US03-Net 3 Days"
}, {
	id : "US04",
	desc : "US04-2% discount if paid within 10 days, Net 30 Days"
}, {
	id : "US05",
	desc : "US05-Net 5 days"
}, {
	id : "US06",
	desc : "US06-2% discount if paid within 15 days, Net 30 Days"
}, {
	id : "US07",
	desc : "US07-2% discount if paid within 20 days, Net 30 Days"
}, {
	id : "US08",
	desc : "US08-1% discount if paid within 15 days, Net 30 Days"
}, {
	id : "US09",
	desc : "US09-2% discount if paid within 10 days, Net 11 Days"
}, {
	id : "US10",
	desc : "US10-Net 10 days"
}, {
	id : "US11",
	desc : "US11-1.5% discount if paid within 10 days, Net 16 Days"
}, {
	id : "US12",
	desc : "US12-1% discount if paid within 14 days, Net 15 Days"
}, {
	id : "US13",
	desc : "US13-2% discount if paid within 15 days, Net 16 Days"
}, {
	id : "US14",
	desc : "US14-3% discount if paid within 10 days, Net 30 Days"
}, {
	id : "US15",
	desc : "US15-Net 15 days"
}, {
	id : "US16",
	desc : "US16-0.5% discount if paid within 10 days, Net 30 Days"
}, {
	id : "US17",
	desc : "US17-2% discount if paid within 10 days, Net 31 Days"
}, {
	id : "US18",
	desc : "US18-10% discount if paid within 10 days, Net 30 Days"
}, {
	id : "US19",
	desc : "US19-5% discount if paid within 20 days, Net 30 Days"
}, {
	id : "US20",
	desc : "US20-Net 20 days"
}, {
	id : "US21",
	desc : "US21-2% discount if paid within 15 days, Net 60 Days"
}, {
	id : "US22",
	desc : "US22-1% discount if paid within 30 days, Net 31 Days"
}, {
	id : "US30",
	desc : "US30-Net 30 days"
}, {
	id : "US50",
	desc : "US50-Net 50 days"
}, {
	id : "US40",
	desc : "US40-Net 40 Days"
}, {
	id : "US45",
	desc : "US45-Net 45 Days"
}, {
	id : "US60",
	desc : "US60-Net 60 Days"
} ];

function init_pmtterms() {
	clr_pmtterms();
	rhsTransfer(true);
	if (usr_comp_cache.paymentScheduleType == 'MONTHLY') {
		jQuery("#schd_wkrw").attr('style', 'display:none');
		jQuery("#schd_mnrw").attr('style', 'display:table-row');
		dwr.util.setValue('schd_mnrw_sel', usr_comp_cache.paymentScheduleValue);
		jQuery("#schmn").attr('checked', true);
	} else {
		dwr.util.setValue('schd_wkrw_sel', usr_comp_cache.paymentScheduleValue);
		if(usr_comp_cache.paymentScheduleType == 'WEEKLY'){
			jQuery("#schd_wkrw").attr('style', 'display:table-row');
			jQuery("#schd_mnrw").attr('style', 'display:none');
			jQuery("#schwk").attr('checked', true);
		}else if(usr_comp_cache.paymentScheduleType == 'BIWEEKLY'){
			jQuery("#schd_wkrw").attr('style', 'display:table-row');
			jQuery("#schd_mnrw").attr('style', 'display:none');
			jQuery("#schbiwk").attr('checked', true);
		}
	}
}

function clr_pmtterms() {
	lhsList = new Array();
	rhsList = new Array();
	dwr.util.removeAllOptions("reg_compPaymentTerms");
	dwr.util.removeAllOptions("reg_compPaymentTermsSelected");

	dwr.util.setValue('schd_wkrw_sel', '');
	dwr.util.setValue('schd_mnrw_sel', '');
	jQuery("#schd_wkrw").attr('style', 'display:none');
	jQuery("#schd_mnrw").attr('style', 'display:none');
	jQuery("#schwk").attr('checked', false);
	jQuery("#schbiwk").attr('checked', false);
	jQuery("#schmn").attr('checked', false);
}

function rhsTransfer(isSourceCache) {
	var selectedValues = new Array();
	lhsList = new Array();
	if (isSourceCache) {
		selectedValues = usr_comp_cache.paymentTerms;
	} else {
		selectedValues = dwr.util.getValue("reg_compPaymentTerms");
	}

	for ( var i = 0; i < paymentTerms.length; i++) {
		var paymentTerm = paymentTerms[i];

		for ( var j = 0; j < selectedValues.length; j++) {
			var selectedId = selectedValues[j];
			if (selectedId == paymentTerm.id) {
				rhsList.push(paymentTerm);
			}
		}
	}

	for ( var i = 0; i < paymentTerms.length; i++) {
		var paymentTerm = paymentTerms[i];

		if (!rhsList.contains(paymentTerm)) {
			lhsList.push(paymentTerm);
		}
	}
	sortPaymentListArray();
	dwr.util.removeAllOptions("reg_compPaymentTerms");
	dwr.util.removeAllOptions("reg_compPaymentTermsSelected");
	dwr.util.addOptions("reg_compPaymentTerms", lhsList, "id", "desc");
	dwr.util.addOptions("reg_compPaymentTermsSelected", rhsList, "id", "desc");
}

function lhsTransfer() {

	var selectedValues = new Array();
	rhsList = new Array();
	selectedValues = dwr.util.getValue("reg_compPaymentTermsSelected");
	if (selectedValues != null && selectedValues.length > 0) {
		for ( var i = 0; i < selectedValues.length; i++) {
			var selectedId = selectedValues[i];
			lhsList.push(getPaymentTerm(selectedId));
			//lhsList.sort();

		}
	}

	for ( var i = 0; i < paymentTerms.length; i++) {
		var paymentTerm = paymentTerms[i];

		if (!lhsList.contains(paymentTerm)) {
			rhsList.push(paymentTerm);
		}
	}

	sortPaymentListArray();
	dwr.util.removeAllOptions("reg_compPaymentTerms");
	dwr.util.removeAllOptions("reg_compPaymentTermsSelected");
	dwr.util.addOptions("reg_compPaymentTerms", lhsList, "id", "desc");
	dwr.util.addOptions("reg_compPaymentTermsSelected", rhsList, "id", "desc");

}

function getPaymentTerm(id) {

	for ( var i = 0; i < paymentTerms.length; i++) {
		var paymentTerm = paymentTerms[i];

		if (paymentTerm.id == id) {
			return paymentTerm;
		}
	}
}

function sortPaymentListArray() {

	lhsList.sort(function(a, b) {
		if ((a.id + "") < (b.id + "")) {
			return -1;
		}
		if ((a.id + "") > (b.id + "")) {
			return 1;
		}
		return 0;
	});

	rhsList.sort(function(a, b) {
		if ((a.id + "") < (b.id + "")) {
			return -1;
		}
		if ((a.id + "") > (b.id + "")) {
			return 1;
		}
		return 0;
	});
}
//////////Company Information Tab////////////////////////////
var usr_comp_cache = null;
//companyInfo_activity_throbber
function loadCompanyInfo() {
	if (usr_comp_cache == null) {
		setup_usercompcache(success_getLoggedInUserCompany);
	} else {
		populateCompanyProfile();

		//populate company locations.
		populateCompanyLocations();
	}

}

function setup_usercompcache(handlerfunc) {
	var dcmd = {
		callback : handlerfunc,
		exceptionHandler : exception_loadCompanyInfo,
		timeout : 100000,
		errorHandler : exception_loadCompanyInfo
	};

	DWR_PurchaseOrders.findCompanyById(usrcompany_uid, dcmd);
}

function exception_loadCompanyInfo() {

}

function populateCompanyProfile() {
	dwr.util.setValue('comp_profile_name', usr_comp_cache.companyName);
	dwr.util.setValue('comp_profile_tax_id', usr_comp_cache.companyTaxId);
	dwr.util.setValue('comp_profile_ssn', usr_comp_cache.companySSN);
	dwr.util.setValue('comp_profile_business', usr_comp_cache.companyDomain);
	dwr.util.setValue('comp_profile_contact_person', usr_comp_cache.contact);
	//dwr.util.setValue('reg_compAddressLine1',usr_comp_cache.addressLine1);
	//dwr.util.setValue('reg_compAddressLine2',usr_comp_cache.addressLine2);
	//dwr.util.setValue('reg_compCity',usr_comp_cache.city);
	//dwr.util.setValue('reg_compState',usr_comp_cache.state);
	//dwr.util.setValue('reg_compZip',usr_comp_cache.zip);
	//dwr.util.setValue('reg_compCountry',usr_comp_cache.country);

	//dwr.util.setValue('reg_compCountry',usr_comp_cache.country);
	dwr.util.setValue('comp_profile_phone', usr_comp_cache.phone);
	dwr.util.setValue('comp_profile_fax', usr_comp_cache.fax);
	dwr.util.setValue('comp_profile_email', usr_comp_cache.email);
	//	reg_areaCodeFax+
	dwr.util.setValue('comp_profile_url', usr_comp_cache.URL);
	dwr.util.setValue('comp_profile_currency', usr_comp_cache.currency);
	
	/*dwr.util.setValue('main_addr1', '');
	dwr.util.setValue('main_addr2', '');
	dwr.util.setValue('main_zipcode', '');
	dwr.util.setValue('main_city_name', '');
	dwr.util.setValue('main_state_name', '');
	dwr.util.setValue('main_cur_loc_id', '');
	dwr.util.setValue('main_country', "");
	document.getElementById('main_use_billing').checked = false;
	document.getElementById('main_use_shipping').checked = false;*/
	
	
	dwr.util.setValue('main_addr1', usr_comp_cache.addressLine1);
	dwr.util.setValue('main_addr2', usr_comp_cache.addressLine2);
	dwr.util.setValue('main_zipcode', usr_comp_cache.zip);
	dwr.util.setValue('main_city_name', usr_comp_cache.city);
	dwr.util.setValue('main_state_name', usr_comp_cache.state);
	dwr.util.setValue('main_country',usr_comp_cache.country);
	

}

function updateCompanyProfile() {

	if (ketchupObj.allFieldsValidYSNOverride(jQuery('#from_company_register'),
			true)) {
		var cid = usr_comp_cache.companyId;
		var regXfer = {};
		regXfer.companyName = dwr.util.getValue("comp_profile_name");
		regXfer.companyLOB = dwr.util.getValue("comp_profile_business");
		regXfer.companyTaxId = dwr.util.getValue("comp_profile_tax_id");
		regXfer.companySsn = dwr.util.getValue("comp_profile_ssn");
		regXfer.companyaddressLine1 = usr_comp_cache.addressLine1; //
		regXfer.companyaddressLine2 = usr_comp_cache.addressLine2; //
		regXfer.companyContact = dwr.util
				.getValue("comp_profile_contact_person");
		regXfer.companyCity = usr_comp_cache.city; //
		regXfer.companyState = usr_comp_cache.state;//
		regXfer.companyZip = usr_comp_cache.zip;//
		regXfer.companyPhoneNumber = dwr.util.getValue("comp_profile_phone");
		regXfer.companyFaxNumber = dwr.util.getValue("comp_profile_fax");
		regXfer.companyEmail = dwr.util.getValue("comp_profile_email");
		//regXfer.companyCountry = dwr.util.getValue("reg_compCountry");//
		regXfer.companyURL = dwr.util.getValue("comp_profile_url");
		regXfer.companyCurrency = dwr.util.getValue("comp_profile_currency");
		regXfer.otherRegId = dwr.util.getValue("comp_profile_otherid_type");
		regXfer.otherRegvalue = dwr.util.getValue("comp_profile_otherid_value");
		regXfer.companyPaymentTerms = usr_comp_cache.paymentTerms;
		regXfer.emailPreferences = usr_comp_cache.emailPreferences;
		regXfer.faxPreferences = usr_comp_cache.faxPreferences;

		jQuery('#companyInfo_activity_throbber').removeClass('throbberOff')
				.addClass('throbberOn');
		var dwrCallMetaData = {
			callback : success_updateCompanyProfile,
			exceptionHandler : exception_updateCompanyProfile,
			timeout : 100000,
			errorHandler : exception_updateCompanyProfile
		};
		//turnThrobberOn('Updating Company Profile');
		DWR_Register.updateCompany(cid, regXfer, dwrCallMetaData);
	}

}

function success_updateCompanyProfile(responseObj) {
	jQuery('#companyInfo_activity_throbber').removeClass('throbberOn')
			.addClass('throbberOff');
	if (responseObj.respCode == 0) {
		usr_comp_cache = responseObj.objRespOrError;
		showusrmessage("Company Information Updated successfully!!");
	} else {
		jQuery('#companyInfo_activity_throbber').removeClass('throbberOn')
				.addClass('throbberOff');
		showusrmessage("Error in Updating Company");
	}

}

function exception_updateCompanyProfile(responseObj) {
	jQuery('#companyInfo_activity_throbber').removeClass('throbberOn')
			.addClass('throbberOff');
	showusrmessage("Error in Updating Company");

}

function resetCompanyProfile() {
	populateCompanyProfile();
}

//////////Company Information Tab End////////////////////////////

//////////Company Locations Tab Start///////////////////////////
function clearlocinfo() {
	dwr.util.setValue('addr1', '');
	dwr.util.setValue('addr2', '');
	dwr.util.setValue('zipcode', '');
	dwr.util.setValue('city_name', '');
	dwr.util.setValue('state_name', '');
	dwr.util.setValue('cur_loc_id', '');
	dwr.util.setValue('country', "");
	document.getElementById('use_billing').checked = false;
	document.getElementById('use_shipping').checked = false;
	dwr.util.setValue('cur_loc_id', null);
	//toggleChannels('div_msg_11','11');
	jQuery('li').removeClass('liselected');
}
function populateCompanyLocations() {
	clearlocinfo();
	populateLeftMenu("test11","Select A Location",populateContentOnLocationMenu);
}

function populateLeftMenu(domParent,menuName,datafunc){
	var e = null;
	var e1 = null;
	var locid = domParent + "_" + "locationLeft";
	jQuery("#" + locid).remove();
	jQuery("#"+ locid+ "UL").remove();
	if( jQuery("#" + locid).length == 0){ // this tells if element is present in dom or not
		 e = jQuery("<div/>", {
			  "class": "title",
			  id : locid,
			  text: menuName,
			  click: function(){		   
				  jQuery(this).toggleClass('selected');
				  jQuery(this).next().slideToggle('fast');
			  }
			});
	} else{
		e = jQuery("#"+locid);
	}
	
	if( jQuery("#"+ locid+ "UL").length == 0){
		e1 = jQuery("<ul/>", {
			  "class": "uiLine",
			  id : locid+"UL"
			  
		});
	} else{
		e1 = jQuery(locid+"#UL");
	}
	
	datafunc(domParent,e,e1);
}

function populateContentOnLocationMenu(domParent,e,e1){
	if (usr_comp_cache != null && usr_comp_cache.locations != null	&& usr_comp_cache.locations.length > 0) {
		var len = usr_comp_cache.locations.length;
		for ( var i = 0; i < len; i++) {
			
			if(jQuery("#bc_loc_editcomm"+i).length == 0){
				
				e1.append(jQuery('<li>', {
					 click: function(){
						editMeLocation(this)
			        },
			        id : "bc_loc_editcomm"+i,
			        text: usr_comp_cache.locations[i].city,
			        "class": "menuList"
			       
			   }));
			}
			
		}
	}
	e.insertAfter(jQuery('#'+domParent));
	e1.insertAfter(e);
}

var cur_loc_id = null;

function editMeLocation(ctrlid) {
	
	jQuery('li').removeClass('liselected');
	jQuery("#"+ctrlid.id).addClass('liselected');
	var idx = Number(ctrlid.id.replace('bc_loc_editcomm', ''));
	var loc = usr_comp_cache.locations[idx];
	dwr.util.setValue('addr1', loc.addressLine1);
	dwr.util.setValue('addr2', loc.addressLine2);
	dwr.util.setValue('zipcode', loc.zip);
	dwr.util.setValue('city_name', loc.city);
	dwr.util.setValue('state_name', loc.state);
	dwr.util.setValue('cur_loc_id', loc.locationId);
	if (isEmptyString(loc.countryCode)) {
		dwr.util.setValue('country', "US");
	} else {
		dwr.util.setValue('country', loc.countryCode);
	}

	if ("Y" == loc.billingAddress) {
		document.getElementById('use_billing').checked = true;
	} else {
		document.getElementById('use_billing').checked = false;
	}

	if ("Y" == loc.shippingAddress) {
		document.getElementById('use_shipping').checked = true;
	} else {
		document.getElementById('use_shipping').checked = false;
	}
	slide_div('div_msg_111');
}

function addNewLocation(){
	clearlocinfo();
	slide_div('div_msg_111');
}



function deleteMeLocation() {
	var ctrlid = jQuery('.liselected')[0];
	var idx = Number(ctrlid.id.replace('bc_loc_editcomm', ''));	
	var loc = usr_comp_cache.locations[idx];
	var conf = confirm('Are you sure you want to delete this Location?');
	if (conf) {
		var dcmd = {
			callback : success_updateCompanyProfileloc,
			exceptionHandler : null,
			timeout : 100000,
			errorHandler : null
		};
		var cid = usr_comp_cache.companyUniqueIdentifier;

		addr = {
			locationId : loc.locationId
		};
		DWR_UserManagement.addUpdateDeleteLocation(addr, cid, true, dcmd);
	}
}

function addupdateloc() {

	if(ketchupObj.allFieldsValidYSNOverride(jQuery('#form_addcomploc'),true)){

	//capture data.
	var loc = {};
	loc.addressLine1 = dwr.util.getValue('addr1');
	loc.addressLine2 = dwr.util.getValue('addr2');
	loc.city = dwr.util.getValue('city_name');
	loc.state = dwr.util.getValue('state_name');
	loc.zip = dwr.util.getValue('zipcode');
	loc.countryCode = dwr.util.getValue('country');
	if (document.getElementById('use_billing').checked) {
		loc.billingAddress = 'Y';
	} else {
		loc.billingAddress = 'N';
	}

	if (document.getElementById('use_shipping').checked) {
		loc.shippingAddress = 'Y';
	} else {
		loc.shippingAddress = 'N';
	}

	var curl = dwr.util.getValue('cur_loc_id');

	if (!isEmptyString(curl)) {
		for ( var i = 0; i < usr_comp_cache.locations.length; i++) {
			if (curl == usr_comp_cache.locations[i].locationId) {
				loc.locationId = curl;
			}
		}
	} else {
		loc.locationId = null;
	}

	jQuery('#bc_cloca_header_throbber').removeClass('notif_throbberOff')
			.addClass('notif_throbberOn');
	var dcmd = {
		callback : success_updateCompanyProfileloc,
		exceptionHandler : null,
		timeout : 100000,
		errorHandler : null
	};

	DWR_UserManagement.addUpdateDeleteLocation(loc,
			usr_comp_cache.companyUniqueIdentifier, false, dcmd);
	}//
}

function success_updateCompanyProfileloc(responseObj) {
	clearlocinfo();
	jQuery('#bc_cloca_header_throbber').removeClass('notif_throbberOn')
			.addClass('notif_throbberOff');
	if (responseObj.respCode == 0) {
		setup_usercompcache(populateCompanyLocations);
		usr_comp_cache = responseObj.objRespOrError;
		showusrmessage("Location Information Updated successfully!!");
	} else {
		jQuery('#bc_cloca_header_throbber').removeClass('notif_throbberOn')
				.addClass('notif_throbberOff');
		showusrmessage("Error in Updating Company");
	}

}
//////////Company Locations Tab End ///////////////////////////

/////////Company Payment Terms Tab Start/////////////////////////
function selpmtschedule(value) {
	if (value == "MONTHLY") {
		jQuery("#schd_wkrw").attr('style', 'display:none');
		jQuery("#schd_mnrw").attr('style', 'display:table-row');
	} else {
		jQuery("#schd_wkrw").attr('style', 'display:table-row');
		jQuery("#schd_mnrw").attr('style', 'display:none');
	}
}

function saveupdpmtinfo() {
	var selPmtTerms = new Array();

	if (rhsList != null && rhsList.length > 0) {
		for ( var i = 0; i < rhsList.length; i++) {
			selPmtTerms.push(rhsList[i].id);
		}
	}

	var sType = null;
	if (document.getElementById('schwk').checked) {
		sType = "WEEKLY";
	} else if (document.getElementById('schbiwk').checked) {
		sType = "BIWEEKLY";
	} else if (document.getElementById('schmn').checked) {
		sType = "MONTHLY";
	}

	var sValue = null;
	if (!isEmptyString(sType)) {
		if (sType == 'MONTHLY') {
			sValue = dwr.util.getValue('schd_mnrw_sel');
		} else {
			sValue = dwr.util.getValue('schd_wkrw_sel');
		}
	}

	var dcmd = {
		callback : success_updateCompanyProfilePmt,
		exceptionHandler : null,
		timeout : 100000,
		errorHandler : null
	};

	DWR_UserManagement.updatePaymentInformation(selPmtTerms, sType, sValue,
			usr_comp_cache.companyUniqueIdentifier, dcmd);

}

function success_updateCompanyProfilePmt(responseObj) {
	if (responseObj.respCode == 0) {
		setup_usercompcache(success_getLoggedInUserCompany);
		showusrmessage("Payment Information Updated successfully!!");
	} else {
		showusrmessage("Error in Updating Company");
	}
}
/////////Company Payment Terms Tab End//////////////////////////


//////// Notification Management Tab Start //////////////////////
function init_noti_prefs(){
	if(usr_comp_cache != null && usr_comp_cache.emailPreferences != null){
		jQuery("#po_sent").attr('checked', usr_comp_cache.emailPreferences.posent);
		jQuery("#po_received").attr('checked', usr_comp_cache.emailPreferences.poreceived);
		jQuery("#inv_sent").attr('checked', usr_comp_cache.emailPreferences.invsent);
		jQuery("#inv_received").attr('checked', usr_comp_cache.emailPreferences.invreceived);
		jQuery("#pymt_sent").attr('checked', usr_comp_cache.emailPreferences.pymtsent);
		jQuery("#pymt_received").attr('checked', usr_comp_cache.emailPreferences.pymtreceived);
		jQuery("#crd_sent").attr('checked', usr_comp_cache.emailPreferences.crdsent);
		jQuery("#crd_received").attr('checked', usr_comp_cache.emailPreferences.crdreceived);
	}else{
		jQuery("#po_sent").attr('checked', false);
		jQuery("#po_received").attr('checked', false);
		jQuery("#inv_sent").attr('checked', false);
		jQuery("#inv_received").attr('checked', false);
		jQuery("#pymt_sent").attr('checked', false);
		jQuery("#pymt_received").attr('checked', false);
		jQuery("#crd_sent").attr('checked', false);
		jQuery("#crd_received").attr('checked', false);
	}
}

function saveupdnoti(){
	var eprf = null;
	if(usr_comp_cache != null && usr_comp_cache.emailPreferences != null){
		eprf = usr_comp_cache.emailPreferences;
	}else {
		eprf = {};
		eprf.id = null;
	}
	
	eprf.communicationMode = 'EMAIL';
	eprf.posent = document.getElementById('po_sent').checked;
	eprf.poreceived = document.getElementById('po_received').checked;
	eprf.invsent = document.getElementById('inv_sent').checked;
	eprf.invreceived = document.getElementById('inv_received').checked;
	eprf.pymtsent = document.getElementById('pymt_sent').checked;
	eprf.pymtreceived = document.getElementById('pymt_received').checked;
	eprf.crdsent = document.getElementById('crd_sent').checked;
	eprf.crdreceived = document.getElementById('crd_received').checked;
	
	var dcmd = {
			callback : success_updateCompanyProfileComPref,
			exceptionHandler : null,
			timeout : 100000,
			errorHandler : null
		};

		DWR_UserManagement.updateCommunicationPrefs(eprf, usr_comp_cache.companyUniqueIdentifier, dcmd);
}

function success_updateCompanyProfileComPref(responseObj){
	if (responseObj.respCode == 0) {
		setup_usercompcache(success_getLoggedInUserCompany);
		showusrmessage("Notification Preferences Updated successfully!!");
	} else {
		showusrmessage("Error in Updating Company");
	}
}
//////// Notification Manangement Tab End ///////////////////////


////////User Group Management Tab Start///////////////////////



function success_saveUserGroup(resp){
	if(resp.respCode == 0){
		showusrmessage("User Group information updated successfully.");
		success_getUserGroup(resp);
	}else{
		showusrmessage("User Group information update failed.");
	}
}

function success_getUserGroup(resp){
	if(resp.respCode == 0){
		usrgrp_cache = resp.objRespOrError;
		init_usrgrp();
	}
}

function saveUserGroup(){
	
		if(isEmptyString(dwr.util.getValue('usrgrp_name'))){
			var form = jQuery('#from_addgroup');
			var el = jQuery('#usrgrp_name');
			var container = null;
			if(jQuery('.ketchup-error').length == 0){
				
				var elOffset = el.offset();
				container  = jQuery('<div/>', {
	                html   : '<ul></ul><span></span>',
	                'class': 'ketchup-error',
	                css    : {
	                           top : elOffset.top,
	                           left: elOffset.left + el.outerWidth() - 20
	                         }
	              });
				container.appendTo('body');
			} else{
				container = jQuery('.ketchup-error');
			}
			ketchupObj.addErrorMessages(form, el, container, ['This field is required.']);
			ketchupObj.showErrorContainer(form, el, container);
			return;
		}
		
		
		
		var ug = new Object();
		var create = false;
		ug.name = dwr.util.getValue('usrgrp_name');
		ug.companyId = usrcompany_uid;
		ug.id=dwr.util.getValue('usrgrp_id');
		ug.privilage = new Object();
		
		if(isEmptyString(ug.id)){
			create = true;
		}else {
			create = false;
		}
		
		
		
		
		ug.privilage.createPO = document.getElementById('p_sendpo').checked;
		ug.privilage.receivePO = document.getElementById('p_recvpo').checked;
		ug.privilage.changePO = document.getElementById('p_chngpo').checked;
		ug.privilage.cancelPO = document.getElementById('p_cancpo').checked;
		ug.privilage.createInvoices = document.getElementById('p_sendinv').checked;
		ug.privilage.receiverInvoices = document.getElementById('p_recvinv').checked;
		ug.privilage.approveInvoices = document.getElementById('p_appvinv').checked;
		ug.privilage.rejectInvoices = document.getElementById('p_rejtinv').checked;
		ug.privilage.createMemos = document.getElementById('p_sendmmo').checked;
		ug.privilage.receiverMemos = document.getElementById('p_recvmmo').checked;
		ug.privilage.approveMemos = document.getElementById('p_appvmmo').checked;
		ug.privilage.rejectMemos = document.getElementById('p_rejtmmo').checked;
		ug.privilage.postPayments = document.getElementById('p_sendpmt').checked;
		ug.privilage.receivePayments = document.getElementById('p_recvpmt').checked;
		ug.privilage.updatePayments = document.getElementById('p_updtpmts').checked;
	
		var dcmd = {
				callback : success_saveUserGroup,
				exceptionHandler : null,
				timeout : 100000,
				errorHandler : null
			};
	
	  DWR_UserManagement.createOrSaveUserGroup(ug,create,dcmd);
  
}

function getUserGroup(){
		
	var dcmd = {
			callback : success_getUserGroup,
			exceptionHandler : null,
			timeout : 100000,
			errorHandler : null
		};

  DWR_UserManagement.getUserGroupList(usrcompany_uid,dcmd);
}


function clear_usrgrp(){
	jQuery("#p_sendpo").attr('checked', false);
	jQuery("#p_recvpo").attr('checked', false);
	jQuery("#p_chngpo").attr('checked', false);
	jQuery("#p_cancpo").attr('checked', false);
	jQuery("#p_sendinv").attr('checked', false);
	jQuery("#p_recvinv").attr('checked', false);
	jQuery("#p_appvinv").attr('checked', false);
	jQuery("#p_rejtinv").attr('checked', false);
	jQuery("#p_sendmmo").attr('checked', false);
	jQuery("#p_recvmmo").attr('checked', false);
	jQuery("#p_appvmmo").attr('checked', false);
	jQuery("#p_rejtmmo").attr('checked', false);
	jQuery("#p_sendpmt").attr('checked', false);
	jQuery("#p_recvpmt").attr('checked', false);
	jQuery("#p_updtpmts").attr('checked', false);
	
	dwr.util.removeAllRows("bc_cgrp_body", {
		filter : function(tr) {
			return (tr.id != "bc_cgrp_pattern");
		}
	});
	
	dwr.util.setValue('usrgrp_name','');
	dwr.util.setValue('usrgrp_id',null);
	
	toggleChannels('div_msg_121','121');
	
}

var usrgrp_cache = null;
function init_usrgrp(){
	
	clear_usrgrp();
	populateLeftMenu("test1211","Custom Groups",populateContentOnGroupsMenu);
	populateLeftMenu("test1211_1","Default Groups",populateContentOnDefaultGroupsMenu);
}

function populateContentOnGroupsMenu(domParent,e,e1){
	if(usrgrp_cache != null && usrgrp_cache.length > 0) {
		var len = usrgrp_cache.length;
		for ( var i = 0; i < len; i++) {
			
			if(jQuery("#bc_cgrp_editcomm"+i).length == 0){
				
				e1.append(jQuery('<li>', {
					 click: function(){
						 editMeGroup(this)
			        },
			        id : "bc_cgrp_editcomm"+i,
			        text: usrgrp_cache[i].name,
			        "class": "menuList"
			       
			   }));
			}
			
		}
	}
	e.insertAfter(jQuery('#'+domParent));
	e1.insertAfter(e);
}

function populateContentOnDefaultGroupsMenu(domParent,e,e1){
	jQuery('#bc_cdefgrp_editcomm').remove();
	e1.append(jQuery('<li>', {
		 click: function(){
			 editMeGroup(this)
       },
       id : "bc_cdefgrp_editcomm_bsu",
       text: "Super User - Buyer Profile",
       "class": "menuList"
      
  }));
	
	e1.append(jQuery('<li>', {
		 click: function(){
			 editMeGroup(this)
      },
      id : "bc_cdefgrp_editcomm_ssu",
      text: "Super User - Supplier Profile",
      "class": "menuList"
     
 }));
	
	e.insertAfter(jQuery('#'+domParent));
	e1.insertAfter(e);
}


function editMeGroup(ctrlid){
	jQuery('li').removeClass('liselected');
	jQuery("#"+ctrlid.id).addClass('liselected');
	
	if(ctrlid.id == 'bc_cdefgrp_editcomm_ssu' || ctrlid.id == 'bc_cdefgrp_editcomm_bsu'){
		jQuery("#p_sendpo").attr('checked', true);
		jQuery("#p_recvpo").attr('checked', true);
		jQuery("#p_chngpo").attr('checked', true);
		jQuery("#p_cancpo").attr('checked', true);
		jQuery("#p_sendinv").attr('checked', true);
		jQuery("#p_recvinv").attr('checked', true);
		jQuery("#p_appvinv").attr('checked', true);
		jQuery("#p_rejtinv").attr('checked', true);
		jQuery("#p_sendmmo").attr('checked', true);
		jQuery("#p_recvmmo").attr('checked', true);
		jQuery("#p_appvmmo").attr('checked', true);
		jQuery("#p_rejtmmo").attr('checked', true);
		jQuery("#p_sendpmt").attr('checked', true);
		jQuery("#p_recvpmt").attr('checked', true);
		jQuery("#p_updtpmts").attr('checked', true);
		jQuery("#b_svusrgrp").attr('disabled',true);
		if(ctrlid.id == 'bc_cdefgrp_editcomm_ssu'){
			dwr.util.setValue('usrgrp_name','Super User - Supplier Profile');
		}else{
			dwr.util.setValue('usrgrp_name','Super User - Buyer Profile');
		}
		
		dwr.util.setValue('usrgrp_id',null);
		
	}else if(usrgrp_cache != null && usrgrp_cache.length > 0){
		jQuery("#b_svusrgrp").attr('disabled',false);
		var idx = Number(ctrlid.id.replace('bc_cgrp_editcomm', ''));
		var grp = usrgrp_cache[idx];
		dwr.util.setValue('usrgrp_name',grp.name);
		dwr.util.setValue('usrgrp_id',grp.id);
		jQuery("#p_sendpo").attr('checked', grp.privilage.createPO);
		jQuery("#p_recvpo").attr('checked', grp.privilage.receivePO);
		jQuery("#p_chngpo").attr('checked', grp.privilage.changePO);
		jQuery("#p_cancpo").attr('checked', grp.privilage.cancelPO);
		jQuery("#p_sendinv").attr('checked', grp.privilage.createInvoices);
		jQuery("#p_recvinv").attr('checked', grp.privilage.receiverInvoices);
		jQuery("#p_appvinv").attr('checked', grp.privilage.approveInvoices);
		jQuery("#p_rejtinv").attr('checked', grp.privilage.rejectInvoices);
		jQuery("#p_sendmmo").attr('checked', grp.privilage.createMemos);
		jQuery("#p_recvmmo").attr('checked', grp.privilage.receiverMemos);
		jQuery("#p_appvmmo").attr('checked', grp.privilage.approveMemos);
		jQuery("#p_rejtmmo").attr('checked', grp.privilage.rejectMemos);
		jQuery("#p_sendpmt").attr('checked', grp.privilage.postPayments);
		jQuery("#p_recvpmt").attr('checked', grp.privilage.receivePayments);
		jQuery("#p_updtpmts").attr('checked', grp.privilage.updatePayments);
	}else{
		dwr.util.setValue('usrgrp_name','');
		dwr.util.setValue('usrgrp_id',null);
		jQuery("#p_sendpo").attr('checked', false);
		jQuery("#p_recvpo").attr('checked', false);
		jQuery("#p_chngpo").attr('checked', false);
		jQuery("#p_cancpo").attr('checked', false);
		jQuery("#p_sendinv").attr('checked', false);
		jQuery("#p_recvinv").attr('checked', false);
		jQuery("#p_appvinv").attr('checked', false);
		jQuery("#p_rejtinv").attr('checked', false);
		jQuery("#p_sendmmo").attr('checked', false);
		jQuery("#p_recvmmo").attr('checked', false);
		jQuery("#p_appvmmo").attr('checked', false);
		jQuery("#p_rejtmmo").attr('checked', false);
		jQuery("#p_sendpmt").attr('checked', false);
		jQuery("#p_recvpmt").attr('checked', false);
		jQuery("#p_updtpmts").attr('checked', false);
		jQuery("#b_svusrgrp").attr('disabled',false);
	}
	
	//toggleChannels('div_msg_1211', '1211');
	slide_div('div_msg_1211');
}

function addNewGroup(){
	jQuery("#b_svusrgrp").attr('disabled',false);
	clear_usrgrp();
	slide_div('div_msg_1211');
}

///// User Group Management Tab End///////////////

///// User Management Tab Start ////////////////
var ctx_authusr_table =  null;
var comp_authusrs_cache = null;
function render_jqUserTable() {
	
	if(ctx_authusr_table != null){
		ctx_authusr_table.fnDestroy();
		ctx_authusr_table = null;
	}
	
	ctx_authusr_table = jQuery('#ctx_common_user_list_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : comp_authusrs_cache,
		"bJQueryUI" : true,
		"bSortClasses" : false,
		
		"aoColumns" : [
		{
			"mDataProp" : "userProfileId",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				return "<input type='radio' name='selProfileForProcessing' onclick='javascript:captureProfile(this.id);' id='selProfile_" + obj.aData.userProfileId +  "' value=''>";
			},
			"bUseRendered" : false
		},  {
			"mDataProp" : "firstName",
			"sClass": "alignCenter",
			"fnRender" : function(obj) { return obj.aData.lastName + ", " + obj.aData.firstName },
			"bUseRendered" : false
		}, {
			"mDataProp" : "emailAddress",
			"sType" : "date",
			"sClass": "alignCenter",
			//"fnRender" : function(obj) {},
			"bUseRendered" : false
		}, {
			"mDataProp" : "userGroupId",
			"sClass": "alignCenter",
			"fnRender" : function(obj) { return getUsrGrpName(obj.aData);},
			"bUseRendered" : false
		}, {
			"mDataProp" : "verified",
			"sClass": "alignCenter",
			"fnRender" : function(obj) { return getUsrStatus(obj.aData);},
			"bUseRendered" : false
		}]
	});
}

function getUsrGrpName(obj){
	var ret = "";
	if(getIsSuperUser(obj.userProfileId)){
		ret =  "Super User";
	}else{
		if(usrgrp_cache != null && usrgrp_cache.length > 0){
			var ln = usrgrp_cache.length;
			for(var o=0;o<ln;o++){
				var g = usrgrp_cache[o];
				if(obj.userGroupId == g.id){
					ret =  g.name;
					break;
				}
			}
		}
	}
	
	return ret;
}

function getIsSuperUser(upid){
	if(usr_comp_cache != null && usr_comp_cache.companyProfileAdmins != null && usr_comp_cache.companyProfileAdmins.length > 0){
		var l=usr_comp_cache.companyProfileAdmins.length;
		for(var q=0;q<l;q++){
			if(usr_comp_cache.companyProfileAdmins[q] == upid){
				return true;
			}
		}
	}
	
	return false;
}

function getUsrStatus(obj){
	if(getIsSuperUser(obj.userProfileId)){
		if(obj.disabled){
			return "Verified, Disabled";
		}else{
			return "Verified";
		}
	}else{
		if(obj.verified){
			if(obj.disabled){
				return "Verified, Disabled";
			}else{
				return "Verified";
			}
		}else{
			return "Not Verified";
		}
	}
	return "";
}

function getAuthorizedUsersForCompany(){
	
	var config = {
			callback : success_getAuthUsersForCompany,
			exceptionHandler : null,
			timeout : 100000,
			errorHandler : null	
	};
	
	DWR_UserManagement.getUserProifileByCompany(usr_comp_cache.companyId,config);
}

function success_getAuthUsersForCompany(responseObj){
	//jQuery("#b_disableUser").attr('disabled', true);
	//jQuery("#b_verifyUser").attr('disabled', true);
	//jQuery("#b_chgGroupUser").attr('disabled', true);
	
	if(responseObj.respCode == 0){
		comp_authusrs_cache = responseObj.objRespOrError;
		
		
		render_jqUserTable();
	}
}

var sluser = null;

function captureProfile(ctrlid){
	var pid = ctrlid.replace('selProfile_','');
	var ln = comp_authusrs_cache.length;
	sluser = null;
	for(var i=0;i<ln;i++){
		if(comp_authusrs_cache[i].userProfileId == pid){
			sluser = comp_authusrs_cache[i];
			jQuery("#b_disableUser").attr('disabled', false);
			
			var su = getIsSuperUser(sluser.userProfileId);
			
			if(su ||  sluser.verified){
				jQuery("#b_verifyUser").attr('disabled', true);
			}else{
				jQuery("#b_verifyUser").attr('disabled', false);
			}
			if(su){
				jQuery("#b_chgGroupUser").attr('disabled', true);
			}else{
				jQuery("#b_chgGroupUser").attr('disabled', false);
			}
			break;
		}
	}
	
	var aData = ctx_authusr_table.fnSettings().aoData;
	
	for(var x=0;x<aData.length;x++){
		jQuery(aData[x].nTr).removeClass('row_selected');
		if(aData[x]._aData.userProfileId == pid){
			jQuery(aData[x].nTr).addClass('row_selected');
		}
	}
	
}
//render_jqUserTable();
var chgrp_dlg = null;
function omodal(){
	if(chgrp_dlg == null){
		chgrp_dlg = jQuery( "#modal-dialog-chgrp" ).dialog({
		
			height: 'auto',
			width: 300,
			modal: true,
			autoOpen: false 
		});
	}
	dwr.util.removeAllRows("chgrp_tbody", {
		filter : function(tr) {
			return (tr.id != "chgrp_tbody_pattern");
		}
	});
	
	if(sluser != null){
		dwr.util.setValue('sluserdetails', 'User: ' + sluser.lastName + ', ' + sluser.firstName + ' (' + sluser.emailAddress + ')');
		
		if(getIsSuperUser(sluser.userProfileId)){
			dwr.util.cloneNode("chgrp_tbody_pattern", {
				idSuffix : "1"
			});
			dwr.util.setValue("chgrp_td1", "This user is Super User. Cannot move this user to another group.");
			jQuery("#chgrp_tbody_pattern1").attr('style', 'display:table-row');
			jQuery("#b_disableUser").attr('disabled', true);
			jQuery("#b_verifyUser").attr('disabled', true);
			jQuery("#b_chgGroupUser").attr('disabled', true);
			jQuery("#b_cancelroupUser").attr('disabled', false);
			
			
			
		}else{
			jQuery("#b_disableUser").attr('disabled', false);
			jQuery("#b_verifyUser").attr('disabled', false);
			jQuery("#b_chgGroupUser").attr('disabled', false);
			jQuery("#b_cancelroupUser").attr('disabled', false);
			if(usrgrp_cache != null && usrgrp_cache.length > 0){	
				var ln = usrgrp_cache.length;
				for(var o=0;o<ln;o++){
					var g = usrgrp_cache[o];
					var id= o+'';
					dwr.util.cloneNode("chgrp_tbody_pattern", {
						idSuffix : id
					});
					
					var name = "<b>" + g.name + "</b>";

					dwr.util.setValue("chgrp_grpname" + id, name, {
						escapeHtml : false
					});
					
					dwr.util.setValue("chggrp_grpid"+ id,g.id);
					
					if(sluser.userGroupId == g.id){
						jQuery("#chgrp_rdo" + id).attr('checked', true);
					}else{
						jQuery("#chgrp_rdo" + id).attr('checked', false);
					}
					jQuery("#chgrp_tbody_pattern" + id).attr('style', 'display:table-row');
					
				}
			}else{
				dwr.util.cloneNode("chgrp_tbody_pattern", {
					idSuffix : "1"
				});
				dwr.util.setValue("chgrp_td1", "No Groups found. Please set up User Groups using User Groups tab.");	
	
				jQuery("#chgrp_tbody_pattern1").attr('style', 'display:table-row');
			}
		}
	}else{
		jQuery("#b_disableUser").attr('disabled', true);
		jQuery("#b_verifyUser").attr('disabled', true);
		jQuery("#b_chgGroupUser").attr('disabled', true);
		jQuery("#b_cancelroupUser").attr('disabled', false);
		dwr.util.cloneNode("chgrp_tbody_pattern", {
			idSuffix : "1"
		});
		dwr.util.setValue("chgrp_td1", "No user selected. Please select a user from Users tab.");
		jQuery("#chgrp_tbody_pattern1").attr('style', 'display:table-row');
	}
	
	jQuery( "#chggrp_activity_throbber").removeClass('throbberOnWhite').addClass('throbberOffWhite');
	jQuery( "#modal-dialog-chgrp" ).dialog('open');
	
}


function ocancelchggrp(){
	jQuery("#b_disableUser").attr('disabled', true);
	jQuery("#b_verifyUser").attr('disabled', true);
	jQuery("#b_chgGroupUser").attr('disabled', true);
	jQuery("#b_cancelroupUser").attr('disabled', false);
	jQuery("input[name='selProfileForProcessing']").attr('checked',false);
	var aData = ctx_authusr_table.fnSettings().aoData;
	
	for(var x=0;x<aData.length;x++){
		jQuery(aData[x].nTr).removeClass('row_selected');
		
	}
}

function donechggrp(){
	var rdos = jQuery("input[name='chgrp_grps']");
	if(rdos == undefined || rdos == null || rdos.length <= 0){
		alert('No groups to change from.');
		jQuery( "#modal-dialog-chgrp" ).dialog('close');
	}else{
		var l = rdos.length;
		for(var s=0;s<l;s++){
			if(rdos[s].checked){
				var grpid = dwr.util.getValue('chggrp_grpid' + rdos[s].id.replace('chgrp_rdo',''));
				jQuery( "#chggrp_activity_throbber").removeClass('throbberOffWhite').addClass('throbberOnWhite');
				
				//DWR Call.
				var config = {
						callback : success_updateUserProfileGroup,
						exceptionHandler : null,
						timeout : 100000,
						errorHandler : null	
				};
				
				DWR_UserManagement.updateUserProfileGroup(sluser.userProfileId, grpid, usr_comp_cache.companyId,config);
				
				break;
			}
		}
	}
}

function success_updateUserProfileGroup(resp){
	jQuery( "#chggrp_activity_throbber").removeClass('throbberOnWhite').addClass('throbberOffWhite');
	showusrmessage('User information changed successfully');
	jQuery( "#modal-dialog-chgrp" ).dialog('close');
	success_getAuthUsersForCompany(resp.objRespOrError);
}

function vrfydisableusr(task){
	if(sluser.userProfileId == usr_profile_cache.userProfileId){
		showusrmessage("You cannot verify/disable your own profile.");
		return;
	}else{
		if(task == 'VERIFY' && (getIsSuperUser(sluser.userProfileId) || sluser.verified)){
			showusrmessage("This user is already verified.");
			return;
		}
	}
	//DWR Call.
	var config = {
			callback : success_updateUserProfileGroup,
			exceptionHandler : null,
			timeout : 100000,
			errorHandler : null	
	};
	var newValue = null;
	
	if(task == 'VERIFY'){
		newValue = "true";
	}else if(task == 'DISABLE'){
		var msg = null;
		if(sluser.disabled){
			msg = 'Are you sure you want to Enable this user?'
			newValue = "false";
		}else{
			msg = 'Are you sure you want to Disable this user?';
			newValue = "true";
		}
		var conf = confirm(msg);
		if (!conf) {
			return;
		}
	}
	DWR_UserManagement.updateUserPropertyAsString(sluser.userProfileId, task, newValue,usr_comp_cache.companyId,config);
}
///// User Management Tab End //////////////////

//js  code for slide  NEW
function slide_div(div_id){
	var options = {};
	var speed   = 500;
	jQuery( "#"+div_id).hide('slide',options,speed);
	jQuery( "#"+div_id).show('slide',options,speed);
	     
}


